package com.ttxs.uaa.api.common;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ttxs.common.core.vo.R;
import com.ttxs.uaa.api.BaseApi;
import com.ttxs.common.core.constant.Api;
import com.ttxs.uaa.entity.SysRole;
import com.ttxs.uaa.entity.SysUserRole;
import com.ttxs.uaa.service.ISysRoleService;
import com.ttxs.uaa.service.ISysUserRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 角色信息表 前端控制器
 * </p>
 *
 * @author 天天向上
 * @since 2021-07-26
 */
@RestController
@RequestMapping(Api.Common.Role.PREFIX)
@RequiredArgsConstructor
public class RoleApi extends BaseApi {
    private final ISysRoleService sysRoleService;
    private final ISysUserRoleService sysUserRoleService;
    @GetMapping
    public R list(@RequestParam("page") int pageNo,
                  @RequestParam("limit") int pageSize,
                  @RequestParam(value = "roleName", required = false) String roleName,
                  @RequestParam(value = "roleKey", required = false) String roleKey,
                  @RequestParam(value = "status", required = false) String status) {
        Page<SysRole> page = sysRoleService.page(Page.of(pageNo, pageSize),
                new LambdaQueryWrapper<SysRole>()
                        .eq(SysRole::getPlatformId, getPlatformId())
                        .like(StringUtils.hasText(roleName), SysRole::getRoleName, roleName)
                        .like(StringUtils.hasText(roleKey), SysRole::getRoleKey, roleKey)
                        .eq(StringUtils.hasText(status), SysRole::getStatus, status)
        );
        return R.ok(page);
    }

    @PostMapping
    public R add(@RequestBody SysRole sysRole) {
        sysRole.setPlatformId(getPlatformId());
        return sysRoleService.save(sysRole) ? R.ok() : R.error("添加角色失败");
    }

    @GetMapping("/{id}")
    public R get(@PathVariable Long id) {
        return R.ok(sysRoleService.getById(id));
    }

    @DeleteMapping("/{id}")
    public R del(@PathVariable Long[] id) {
        List<SysUserRole> list = sysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getRoleId, id));
        if(!list.isEmpty()) {
            return R.error("无法删除！角色下有" + list.size() + "个用户");
        }
        return R.ok(sysRoleService.removeByIds(Arrays.asList(id)));
    }

    @PutMapping("/{id}")
    public R update(@PathVariable Long id, @RequestBody SysRole sysRole) {
        sysRole.setRoleId(id);
        sysRole.setPlatformId(getPlatformId());
        return R.ok(sysRoleService.saveOrUpdate(sysRole));
    }
}
